import React from "react";
import { Form, Input, Button, Card, Tooltip } from "antd";
import {
  UserOutlined,
  LockOutlined,
  SunOutlined,
  MoonOutlined,
} from "@ant-design/icons";
import { useNavigate, useLocation } from "react-router-dom";
import { useTheme } from "../../contexts/ThemeContext";
import { getUserPermission, login } from "@/api";
import type { LoginParams } from "@/api";
import { useUserStore } from "@/stores/userStore";

const Login: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { isDarkMode, toggleTheme } = useTheme();
  const [form] = Form.useForm();

  const { setToken, setUserInfo, setLoggedIn, setPermissions, permissions } = useUserStore();

  const onFinish = async (values: LoginParams) => {
    try {
      const res = await login(values);
      console.log("res", res);
      // 判断业务状态码
      if (res.code === 200) {
        // 使用Zustand存储用户状态
        setToken(res.data.token);
        setUserInfo(res.data.userInfo);
        setLoggedIn(true);
        // 设置权限数据
        // setPermissions(res.data.permissions);
        if(permissions.length === 0) { 
          const resp = await getUserPermission();
          console.log("resp", resp);
          setPermissions(resp.routes);
        }
        // 获取重定向地址
        const from = (location.state as { from?: string })?.from || "/";
        // 跳转到之前的页面或首页
        navigate(from, { replace: true });
      }
    } catch (error) {
      // 错误处理已经在request中统一处理
      console.error("登录失败:", error);
    }
  };

  return (
    <div
      style={{
        height: "100vh",
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        background: isDarkMode ? "#141414" : "#f0f2f5",
        position: "relative",
      }}
    >
      <Tooltip title={isDarkMode ? "切换到浅色模式" : "切换到深色模式"}>
        <Button
          type="text"
          icon={isDarkMode ? <SunOutlined /> : <MoonOutlined />}
          onClick={toggleTheme}
          style={{
            color: isDarkMode ? "#fff" : "#000",
            position: "absolute",
            top: "20px",
            right: "20px",
            fontSize: "20px",
          }}
        />
      </Tooltip>
      <Card
        title="系统登录"
        style={{
          width: 400,
          boxShadow: "0 4px 12px rgba(0,0,0,0.1)",
          background: isDarkMode ? "#1f1f1f" : "#fff",
        }}
      >
        <Form
          form={form}
          name="login"
          onFinish={onFinish}
          autoComplete="off"
          size="large"
        >
          <Form.Item
            name="user"
            rules={[{ required: true, message: "请输入用户名！" }]}
          >
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>

          <Form.Item
            name="pwd"
            rules={[{ required: true, message: "请输入密码！" }]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
